package de.gwtprime.client.widgets;

import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.PrimeRequestFactory;
import de.gwtprime.client.user.ACLManager;
import de.gwtprime.client.user.ACLManager.PrimeUIElement;
import de.gwtprime.shared.requestFactory.ArticleCommentProxy;
import de.gwtprime.shared.requestFactory.request.ArticleCommentRequest;
import de.gwtprime.shared.util.UnitConverter;

public class CommentWidget extends Composite {

	interface CommentWidgetUiBinder extends UiBinder<Widget, CommentWidget>{};
	CommentWidgetUiBinder uiBinder = GWT.create(CommentWidgetUiBinder.class);
	
	@UiField Label commentText;
	@UiField Label userName;
	@UiField Label timePosted;
	@UiField Button deleteBtn;
	
	public CommentWidget(final ArticleCommentProxy articleComment, final ClientFactory clientFactory) {
		initWidget(uiBinder.createAndBindUi(this));
		commentText.setText(articleComment.getText());
		deleteBtn.setText("delete");
		timePosted.setText(articleComment.getDate() == null ? "gerade eben" : UnitConverter.convertInputFitting(articleComment.getDate()));
		userName.setText(articleComment.getUserName());
		
		
		deleteBtn.setVisible(ACLManager.hasUserAccess(clientFactory.getUser(), PrimeUIElement.CommentDelete));
		
		deleteBtn.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {

				CommentWidget.this.setVisible(false);
				final PrimeRequestFactory requestFactory = clientFactory
						.getRequestFactory();
				final ArticleCommentRequest request = requestFactory
						.articleCommentRequest();
				Request<Void> createReq2 = request.remove().using(articleComment);

				createReq2.fire(new Receiver<Void>() {
					@Override
					public void onSuccess(Void list) {
						System.out.println("success");
					}

					@Override
					public void onFailure(ServerFailure error) {
						System.out.println("failed");
					}
				});
				
			}
		});
	}
	
	
}
